<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px">
      <div v-for="(val,ind) in value" :key="'val'+ind" style="width:500px">
        <div v-if="val.flag">
          <el-form-item label="密保问题">
            <el-select @change="selectChange(ind)" v-model="val.question" placeholder="请选择密保答案">
              <el-option
                v-for="(item,index) in questions"
                :key="'que'+index"
                :label="item.question"
                :value="item.question"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="密保答案">
            <el-input v-model="val.answer"></el-input>
          </el-form-item>
        </div>
      </div>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  data() {
    return {
      id: this.$store.state.Logins.id,
      form: {},
      questions: [
        { question: '你得幼儿园老师?' },
        { question: '你得小学老师?' },
        { question: '你得中学学老师?' },
        { question: '你得大学老师?' },
        { question: '你的生日?' },
        { question: '你母亲的生日?' },
        { question: '你父亲的生日?' },
        { question: '你最喜欢的宠物?' },
        { question: '你最爱人的名字?' },
        { question: '你爱人的生日?' }
      ],
      value: [
        { answer: '', flag: true },
        { answer: '', flag: false },
        { answer: '', flag: false }
      ],
      questionID: 0
    }
  },
  methods: {
    ...mapActions({
      setQuestion: 'Logins/setQuestion',
      getQuestion: 'Logins/getQuestion'
    }),
    async onSubmit() {
      const res = await this.setQuestion({ jsarr: JSON.stringify(this.value), id: this.id,questionID:this.questionID })
      if (res.data.success) {
        this.$message({
          message: '恭喜你，设置密保成功',
          type: 'success'
        });
      } else {
        this.$message.error('设置密保失败');
      }
    },
    selectChange(index) {
      for (let i = 0; i < this.questions.length; i++) {
        if (this.value[index].question == this.questions[i].question) {
          this.questions.splice(i, 1)
        }
      }
      if (this.value.length - 1 === index) return
      this.value[index + 1].flag = true
    }
  },
  async mounted() {
    const res = await this.getQuestion({ id: this.id })
    if (res.data.data.resultes.length) {
      console.log(res.data.data.resultes[0])
      this.value = JSON.parse(res.data.data.resultes[0].question)
      this.questionID = res.data.data.resultes[0].id
    }

  }
}
</script>

<style scoped>
.el-select {
  width: 100%;
}
</style>